package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import cn.com.elite.Util;
import java.net.URLEncoder;
import cn.com.kh.getProperty;


import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

/**
 *
 * @Title: BP_WG_apiUnderdelivery* @Description:深圳宝安排水系统-网格化 工单数据下送接口--内部
 * @author: chieh* @date 2020-08-05 下午18:00:00
 *
 */


public class BP_WG_apiUnderdelivery implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(BP_WG_apiUnderdelivery.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = list.get(0).get("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            // 调用处理信息
            JSONObject inObject = new JSONObject(inData);
            log.debug("处理前的Json：" + inObject.toString());

            String sys_source = GetJV(inObject, "sys_source");
            String sys_flag = GetJV(inObject, "sys_flag");//1下送2处理回退
            String workorderid = GetJV(inObject, "workorderid");
            log.debug("解析信息- sys_source：" + sys_source + 'sys_flag：' + sys_flag + 'workorderid：' + workorderid);

            def getSelectSQL = eliteBean.chaxun_sql("select o.curstep_id_map as curstep_id_map from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  where o.workorderid= '" + workorderid + "'", "dataSource");
            log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());
            String curstep_id_map = null;
            if (getSelectSQL.size() > 0) {
                curstep_id_map = getSelectSQL.get(0).get("curstep_id_map");
                log.debug("工单步骤流程id：	" + curstep_id_map);
            } else {
                String dealMessage = "当前处理的工单在CRM系统不存在！";
                return "{\"resultcode\":\"0\",\"resultmessage\":\"\",\"data\":\"" + dealMessage + "\"}";
            }

            //结案管理
            if (sys_source == 'WGH' && sys_flag == '1' ) {//&& curstep_id_map == 'KNGZL4'
                outData = WGHCaseClosed(sys_source, workorderid, eliteBean);
            //回退2
            } else if (sys_source == 'WGH' && sys_flag == '2' && curstep_id_map == 'O70W2B') {
                outData = WGHBack(sys_source, workorderid, eliteBean);
            } else {
                String dealMessage = "当前处理的工单在CRM系统工单步骤不在话务员处理:" + curstep_id_map + "节点！";
                return "{\"resultcode\":\"0\",\"resultmessage\":\"\",\"data\":\"" + dealMessage + "\"}";
            }

        } catch (Exception e) {// 失败返回
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):2\",\"data\":[]}";

        }
        log.debug("完成返回结果:" + outData);

        return outData;
    }

    //调用网格化退单接口
    public static String WGHBack(String sys_source, String workorderid, EliteBean eliteBean) {
        long startTime = System.currentTimeMillis();
        def szhtok;
        def szhtokresult = eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'WGHTOK' and MODIFIEDDATE>dateadd(hour,-2,GETDATE())", "dataSource");
        if (szhtokresult.size() > 0) {
            szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
            log.debug("szhtok:	" + szhtok);
        }
        if (szhtok == null) {
            szhtok = getCaseTasks(eliteBean);
        }
        log.debug("szhtok1:	" + szhtok);
        def getSelectSQL = eliteBean.chaxun_sql("select o.workorderid as workorderid,s.staffname as staffname,o.modifieddate as modifieddate,o.comments as comments from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  LEFT JOIN staff s on o.handleby_id=s.staff_id  where o.workorderid= '" + workorderid + "'", "dataSource");
        String eventid = getSelectSQL.get(0).get("workorderid");
        String rectime = getSelectSQL.get(0).get("modifieddate");
        String recuser = getSelectSQL.get(0).get("staffname");
        String content = getSelectSQL.get(0).get("comments");
		String link="退回";
		String company=recuser+"@宝安排水客服系统";
        String injson = "[{\"eventid\":\"" + eventid + "\",\"recuser\":\"" + company + "\",\"link\":\"" + link + "\",\"rectime\":\"" + rectime + "\",\"content\":\"" + content + "\"}]";

        String URL = getProperty.get("WGH.URL");
        String charset = "utf-8";
        int timeout = 30000;
        String SOAPAction = "http://tempuri.org/EventBack"
        String reJson = null;
        try {

            def xmlbody = """<?xml version="1.0" encoding="utf-8"?>
			<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
			  <soap:Body>
			    <EventBack xmlns="http://tempuri.org/">
			      <sParam>""" + injson + """</sParam>
				  <sToken>""" + szhtok + """</sToken>
			    </EventBack>
			  </soap:Body>
			</soap:Envelope>""";

            log.debug("调用接口发送报文信息：" + xmlbody);

            def xml = Util.callWebService(URL, xmlbody, charset, SOAPAction, timeout);
            xml = Util.Transform(xml); //去命令空间
            xml = new XmlParser().parseText(xml); //xml解析
            log.debug("调用退回案件结果返回：" + xml);

            String Resultcode = "";
            String resultmsg = "";
            try {
                Resultcode = xml.Body.EventBackResponse.EventBackResult.text();
                resultmsg = xml.Body.EventBackResponse.sErrMsg.text();
            } catch (Exception e) {
                Resultcode = "";
                resultmsg = "";
                log.error("EM:", e);
            };
            log.debug("LoginResult:	" + Result);

            long endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"" + 1 + "\",\"resultmessage\":\"BP智慧化网格化回退接口处理成功，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":\"" + resultmsg + "\"}";
        } catch (JSONException e) {
            long endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化网格化回退接口处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
        }
        return reJson;
    }

    //调用网格化结案接口
    public static String WGHCaseClosed(String sys_source, String workorderid, EliteBean eliteBean) {
        long startTime = System.currentTimeMillis();
        def szhtok;
        def szhtokresult = eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'WGHTOK' and MODIFIEDDATE>dateadd(hour,-2,GETDATE())", "dataSource");
        if (szhtokresult.size() > 0) {
            szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
            log.debug("szhtok:	" + szhtok);
        }
        if (szhtok == null) {
            szhtok = getCaseTasks(eliteBean);
        }
        log.debug("szhtok1:	" + szhtok);

        def getSelectSQL = eliteBean.chaxun_sql("select o.objective_guid as objective_guid,o.workorderid as workorderid,s.staffname as staffname,o.modifieddate as modifieddate,o.comments as comments from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid  LEFT JOIN staff s on o.handleby_id=s.staff_id  where o.workorderid= '" + workorderid + "'", "dataSource");
        String objective_guid = getSelectSQL.get(0).get("objective_guid");
        String eventid = getSelectSQL.get(0).get("workorderid");
        String rectime = getSelectSQL.get(0).get("modifieddate");
        String recuser = getSelectSQL.get(0).get("staffname");
        String content = getSelectSQL.get(0).get("comments");
		String company=recuser+"@宝安排水客服系统";
		String TPURL = getProperty.get("CRM.TPURL");

        def getSelectUploadSQL = eliteBean.chaxun_sql("select case type when	3  then '"+TPURL+"'+path  else Replace(path,'http://10.44.85.12:8080','http://121.15.5.156:8004') end as path,name,OPERATIONTIME,filedesc from rm_uploadrecord where type in ('3','4')  and  objectiveid='"+objective_guid+"'","dataSource");
        Map<String, Object> map = new HashMap<String, Object>();
        JSONArray json = new JSONArray();
        for (int i = 0; i < getSelectUploadSQL.size(); i++) {
            JSONObject jo = new JSONObject();
            jo.put("path", getSelectUploadSQL.get(i).get("path"));
            jo.put("name", getSelectUploadSQL.get(i).get("name"));
            jo.put("OPERATIONTIME", getSelectUploadSQL.get(i).get("OPERATIONTIME"));
            jo.put("filedesc", getSelectUploadSQL.get(i).get("filedesc"));
            json.put(jo);
        }
        log.debug("getSelectUploadSQL:"+getSelectUploadSQL);
        log.debug("json"+json);

        String injson = "[{\"eventid\":\"" + eventid + "\",\"link\":\"办结\",\"recuser\":\"" + company + "\",\"rectime\":\"" + rectime + "\",\"content\":\"" + content + "\",\"nextorgname\":\"宝安排水 单位\",\"att\":"+json.toString()+"}]";

        String URL = getProperty.get("WGH.URL");
        String charset = "utf-8";
        int timeout = 30000;
        String SOAPAction = "http://tempuri.org/EventFlow"
        String reJson = null;
        try {

            def xmlbody = """<?xml version="1.0" encoding="utf-8"?>
			<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">  
			  <soap:Body> 
			    <EventFlow xmlns="http://tempuri.org/">  
			      <sParam>""" + injson + """</sParam>
				  <sToken>""" + szhtok + """</sToken>
			    </EventFlow> 
			  </soap:Body> 
			</soap:Envelope>""";

            log.debug("调用接口发送报文信息：" + xmlbody);

            def xml = Util.callWebService(URL, xmlbody, charset, SOAPAction, timeout);
            xml = Util.Transform(xml); //去命令空间
            xml = new XmlParser().parseText(xml); //xml解析
            log.debug("调用完结案件结果返回：" + xml);

            String resultcode = "";
            String resultmsg = "";
            try {
                resultcode = xml.Body.EventFlowResponse.EventFlowResult.text();
                resultmsg = xml.Body.EventFlowResponse.sErrMsg.text();
            } catch (Exception e) {
                resultcode = 0;
                resultmsg = "";
                log.error("EM:", e);
            };
            log.debug("resultcode:	" + resultcode);
            log.debug("resultmsg:	" + resultmsg);

            long endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"" + 1 + "\",\"resultmessage\":\"BP智慧化网格化结案接口处理成功，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":\"" + resultmsg + "\"}";
        } catch (JSONException e) {
            long endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"BP智慧化网格化结案接口处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
        }
        return reJson;
    }

    // 获取token
    public static String getCaseTasks(EliteBean eliteBean) {
        log.debug("-------------------------start Bp_Get_WGToKen 开始-----------------");
        def sysurl = "http://127.0.0.1:8080/EliteGeneralHttpTask/GeneralService/Bp_Get_WGToKen";
        String reJson = Util.doHttpGet(sysurl, "UTF-8", 10000, 0);
        JSONObject inObject = new JSONObject(reJson);
        //log.debug("ToKen报文："+inObject);

        String resultcode = GetJV(inObject, "resultcode");
        String data = GetJV(inObject, "data");
        //log.debug("resultcode	"+resultcode);
        //log.debug("data	"+data);

        return data;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        return Rev_Value;
    }

}
